import tushare as ts
import common.constants as const
import tablib as tb
import pandas as pd
import os

class HQHelperTuShare:
    _instance = None #类变量，用于存储单例实例, 负责跟TuShare交互
    _pro = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance: # 为null说明还没有从创建实例
            # 调用父类的__new__方法创建实例
            cls._instance = super(HQHelperTuShare, cls).__new__(cls)

        return cls._instance
    

    def __init__(self):        
        self._pro = ts.pro_api(const.TUSHARE_TOKEN)
        self.path = const.DIC_PATH_RAWDATA
        

    def get_kline_day_by_code(self, code, start_date, end_date):
        # df = self._pro.daily(ts_code=code, start_date=start_date, end_date=end_date, freq=freq, ktype=ktype)
        df = self._pro.fut_daily(ts_code=code, start_date=start_date, end_date=end_date)
        
        if df is not None:
            df.Name = code

        return df
    
    def get_kline_day_by_trade_date(self, code_list, trade_date):
        """如果不传exchange参数，则默认获取所有交易所的日线数据
        ts_code = 'SA.ZCE,RM.ZCE,RB.SHF,EG.DCE,FG.ZCE'
        self._pro.fut_daily(trade_date= trade_date, exchange= exchange)
        一般很少获取单个市场所有数据的场景，改为获取特定期货的数据
        """
        
        # df = self._pro.daily(ts_code=code, start_date=start_date, end_date=end_date, freq=freq, ktype=ktype)
        # fields='ts_code,trade_date,pre_close,pre_settle,open,high,low,close,settle,vol'
        # df = self.pro.fut_daily(trade_date= trade_date, exchange= exchange)
        df = self.pro.fut_daily(ts_code = code_list, trade_date=trade_date)

        return df
    
    def save(self, df, filename = None, mode = 'w'):
        """默认覆盖以前的文件"""
        if not filename:
            filename = f'kline_{df.Name}.csv'

        with open(self.path + filename,mode, newline='') as f: # 加上newline参数，避免空行； w: 覆盖写入； a: 追加写入
            f.write(tb.Dataset().load(df.to_csv(index=False)).export('csv'))

    def save_progress(self, df, filename = None):
        if not filename:
            filename = f'progress.csv'

        # df.to_csv(index=False, path_or_buf=self.path + filename, mode='a+')
        file = self.path + filename
        if not os.path.exists(file):
            df.to_csv(index=False, path_or_buf=file, mode='w')
        else:          
            with open(file, 'a+', newline='') as f: # 加上newline参数，避免空行
                f.write(tb.Dataset().load(df.to_csv(index=False, header=False)).export('csv'))

    def get_progress(self,code):
        df = pd.read_csv(self.path + f'progress.csv')

        return df[df['code'] == code]